<template>
  <div>
      <div >
        <mt-field class='mgtop10 after' :state="state.username" v-model="data.username" :attr="{ 'maxlength': 20 }" label="新手机号"></mt-field>
        <mt-field class='after' :attr="{'maxlength': 6 }" :state="state.verifyCode" v-model="data.verifyCode" label="短信验证码">
          <mt-button height="45px" width="100px" :disabled="smsCount>0"  @click="sendSmsForChange" type="default">{{smsLabel}}</mt-button>
        </mt-field>
      </div>
    <div class="padlr10">
      <mt-button size="large" type="primary" @click="changePhone()">变更手机</mt-button>
    </div>
  </div>
</template>

<script>
  import { Toast } from 'mint-ui';
  var InterValObj;
  let attrs = [{name:'username',reg:/^1[34578]\d{9}$/},
    {name:'verifyCode',reg:/.{6}/}];
  export default {
    name: "changePhone",
    data() {
      return {
        switchValue: true
        ,smsCount:0
        ,data:{}
        ,state:{username:'',verifyCode:''}
      }
    },
    computed: {
      //计算属性
      mytype: function () {
        return this.switchValue ? 'password' : ''
      },
      smsLabel:function(){
         return this.smsCount ==0?"发送验证码":this.smsCount+"秒再获取";
      }
    },
    watch:{data:{
        handler(newVal,oldVal){
          attrs.forEach(n=>{
            if(newVal[n.name]==undefined||newVal[n.name]==''){
              this.state[n.name] = "";
            }else{
              this.state[n.name] = n.reg.test(newVal[n.name])?'success':'error';
            }
          })
        },
        deep:true
      }
    },
    methods:{
      sendSmsForChange:function(){
        let vm = this;
        if(this.state['username']!='success'){
          Toast("请输入正确手机号码！");
          return;
        }
        vm.smsCount = 60;
        this.$http.get("/auth/sendSmsForChange?phone="+this.data.username).then((resp)=>{
             if(resp.code == 0){
                   InterValObj = window.setInterval(()=>{
                  if(vm.smsCount>0){
                    vm.smsCount--
                  }else{
                    clearInterval(InterValObj);
                  }
                }, 1000);
             }else{
               vm.smsCount = 0;
               Toast(resp.msg);
             }
        })
      },
      changePhone:function(){
        let vm = this;
        let attr = attrs.find(n=>{return vm.state[n.name]!='success'})
        if(attr){
           Toast(attr.name+"输入错误!");
           return;
        }
        this.$http.post("/auth/changePhone",changeDataType(this.data)).then((resp)=>{
           if(resp.code == 0){
             Toast("修改成功,请登录！");
             vm.$router.push({path:"/login/login"})
           }else{
             Toast(resp.msg);
           }
        })
      }
    }
  }
</script>

<style scoped>
.padlr10{
  padding:10px;
}
  .mgtop10{
    margin-top: 10px;
  }

</style>
